package com.roc.web.action.terminal;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.common.Excel2007TermFileProcessor;
import com.roc.common.FileProcessor;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TblDictionaryItem;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.impl.MerchantServiceImpl;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.TerminalBrand;
import com.roc.util.constant.TerminalName;
import com.roc.util.constant.TerminalType;
import com.roc.web.action.MerchantSearchCondition;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termSn")
public class TermSnBelongAction extends PaginationBaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = LogManager.getLogger(TermSnBelongAction.class);
	private TermSnBelongSearchCondition searchCondition;
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	@Autowired
        IorgService orgService;
	
        @Autowired
	IPagenitionService pagenitionService;
        @Autowired
        IPageService pageService; //走备库
        
	@Autowired
	IMerchantServices merchantServices;
	
	@Autowired
        ITerminalService terminalService;
        
	
	@Action(value = "termSnBelongInit",
			results = { @Result(location = "/pages/terminal/termSnBelongQuery.jsp") })
	public String termAllotRecallInfoAction() throws Exception {
		try{
			
			initSomeDataForAction();
		}catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("基本信息初始化失败");
		}
		return SUCCESS;
	}
	
    @Action(value = "termSnBelongSearch", results = {
            @Result(name = "success", location = "/pages/terminal/termSnBelongQuery.jsp") })
    // 查询可撤回终端序列号信息
    public String search() throws Exception {
        Operators loginOperators = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
        List<Long> idList = null;
        if (searchCondition == null) {
            searchCondition = (TermSnBelongSearchCondition) getSearchConditionFromSession();
            if (searchCondition == null) {
                searchCondition = new TermSnBelongSearchCondition();
            }
        }
        try {
            initSomeDataForAction();

            // 查询 当前代理商及子代理商 数据
            if(Role.AGENT.getCode().equals(loginOperators.getRoleType())){//代理商
                String agentId= String.valueOf(loginOperators.getId());
                searchCondition.setAgentId(agentId);
            }else if(Role.AGENT_BUSS.getCode().equals(loginOperators.getRoleType())){//业务员
                searchCondition.setOpId(String.valueOf(loginOperators.getSuperiorId()));
            }else if(Role.MERCHANT.getCode().equals(loginOperators.getRoleType())){//商户号
                searchCondition.setMerNo(String.valueOf(loginOperators.getAccountNo()));
            }
            int rows = pageService.countSQL(searchCondition);
            if (rows > 0) {
                searchRsList = pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()),
                        Constance.PAGE_MAX_SIZE);
            }
            List<YjPosInfo> posList = new ArrayList<YjPosInfo>();
            if (searchRsList != null && searchRsList.size() > 0) {
                Iterator iterator = searchRsList.iterator();
                String value = "";
                while (iterator.hasNext()) {
                    Object[] obj = (Object[]) iterator.next();
                    YjPosInfo pos = new YjPosInfo();
                    pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));
                    pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(Constance.Null2EmptyTrim(obj[1])));
                    pos.setPosType(ConfigMerinfoUtil.getPosType(Constance.Null2EmptyTrim(obj[2])));
                    pos.setPosName(ConfigMerinfoUtil.getPosMODEL(Constance.Null2EmptyTrim(obj[3]),
                            Constance.Null2EmptyTrim(obj[1])));
                    pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
                    pos.setIsBind(Constance.Null2EmptyTrim(obj[5]));
                    // pos.setAgentId(Long.valueOf(Constance.Null2EmptyTrim(obj[6])));
                    pos.setAgentName(Constance.Null2EmptyTrim(obj[7]));
                    pos.setIsUsed(Constance.Null2EmptyTrim(obj[8]));
                    pos.setDtCreate((Date) obj[9]);
                    pos.setDtLostmod((Date) obj[10]);
                    pos.setRemark(Constance.Null2EmptyTrim(obj[11]));
                    pos.setMercCode(Constance.Null2EmptyTrim(obj[12]));
                    pos.setTermCode(Constance.Null2EmptyTrim(obj[13]));
                    posList.add(pos);
                }
            }
            searchRsList.clear();
            searchRsList.addAll(posList);
            this.setTotalPage(this.calcuTotalPage(rows));
            getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
            getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
            getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
            setSearchToConditionSession(searchCondition);
            addActionMessage("当前条件下查询到终端序列号总计【" + rows + "】个");
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            addActionError(e.getMessage());

        }

        return SUCCESS;
    }
	
	
	
	@Override
	public void initSomeDataForAction() {
		// TODO Auto-generated method stub
		super.initSomeDataForAction();
		try{
			//查询品牌
		        TblDictionaryItem itemBrand = new TblDictionaryItem();
	   /*             Map<String,String> brandMap = terminalService.selBrandItemByType(itemBrand);

	                Map<String,String> modelMap=new TreeMap<String, String>();
	                
	                TblDictionaryItem item = new TblDictionaryItem();
	                Map<String,String> typeMap = terminalService.selTypeItemByType(item);*/
	                
	                orgList=orgService.queryOrgList();
                        
	                getRequest().setAttribute("orgList", orgList);

	    			getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
	    			getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
	    			getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
			
		}catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
		}
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_TERM_SN_BELONG_QUERY, searchCondition);

	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermSnBelongSearchCondition)getSession().getAttribute(SEARCH_SESSION_TERM_SN_BELONG_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public TermSnBelongSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TermSnBelongSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

        public List<TblInsInf> getOrgList() {
            return orgList;
        }
        
        public void setOrgList(List<TblInsInf> orgList) {
            this.orgList = orgList;
        }

	
	


	
	
}
